package com.you.redis.hash;

import com.you.redis.util.JedisUtils;
import com.you.redis.util.SerializeUtils;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试Redis中的Hash数据类型
 */
public class RedisHashDemo {

    public static void main(String[] args) throws Exception {
        //testSetHashMap();
        testSetObject();
    }

    public static void testSetObject() throws Exception {
        Order order1 = new Order();
        order1.setOrderNo("order:001");
        order1.setOrderName("order:001:name");
        order1.setCount(1);
        order1.setPrice(new BigDecimal("1.00"));
        order1.setCreateTime(new Date());
        Jedis jedis = JedisUtils.getInstance().getJedis();
        //存入订单信息，由于redis的value不支持对象类型，需要先对对象类型进行序列化，再存入
        jedis.hset("user:001:order:001".getBytes(), "order".getBytes(), SerializeUtils.serialize(order1));
        //取出订单信息
        byte[] orderInfoBytes = jedis.hget("user:001:order:001".getBytes(), "order".getBytes());
        Order result = (Order) SerializeUtils.unSerialize(orderInfoBytes);
        if (result != null) {
            System.out.println(result.toString());
        } else {
            System.out.println("----get order result is null----" + result);
        }
    }

    public static void testSetHashMap() throws Exception {
        Jedis jedis = JedisUtils.getInstance().getJedis();
        Map<String, String> map = new HashMap<>();
        map.put("userName", "lisi");
        map.put("age", "22");
        map.put("gender", "男");
        //使用 hmset 设置值
        jedis.hmset("user", map);
        // hmget 获取值 取出user中的name 后面key可以跟多个
        List<String> result = jedis.hmget("user", "userName", "age", "gender");
        System.out.println(result);

        //删除某个键值hdel
        jedis.hdel("user", "age");

        //获取数据
        System.out.println(jedis.hmget("user", "age"));//null
        System.out.println(jedis.hlen("user"));//获取user存放的个数 //2
        System.out.println(jedis.exists("user"));//获取是否存在 user key //true
        System.out.println(jedis.hkeys("user"));//返回map所有的key
        System.out.println(jedis.hvals("user"));//获取map对象中所有的value
    }
}
